<?php

namespace App\Http\Service\Douban;

use App\Models\Doubanpost;
use App\Models\Doubanlog;
use App\Models\Doubanlike;
use App\Models\Doubancollect;
use App\Http\Service\UserService;
use App\Http\Service\Douban\DoubanpostimageService;
use App\Http\Service\BaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use App\Http\Service\ContentScoringService;
use App\Http\Service\Douban\DoubanpostproductService;
use App\Http\Service\AdmindeletelogService;


class DoubanpostService  extends BaseService
{
    private $model;
    public $URL_MAP;
    public $getInfo;
    public function __construct(Doubanpost $model,UserService $userService,Doubanlog $doubanlog,DoubanpostimageService $DoubanpostimageService,Doubanlike $doubanlike,DoubanpostproductService $doubanpostproductService,AdmindeletelogService $admindeletelogService)
    {
        parent::__construct();
        $this->URL_MAP=config('myurl.URL_MAP');
        $this->getInfo=config('myurl.getInfo');
        $this->model = $model;
        $this->doubanlog = $doubanlog;
        $this->userService = $userService;
        $this->DoubanpostimageService = $DoubanpostimageService;
        $this->doubanlike = $doubanlike;
        $this->doubanpostproductService=$doubanpostproductService;
        $this->admindeletelogService=$admindeletelogService;
    }
   
    /**
     *
     * @param array $params
     * @return array
     */
    public function addData($request,$data=[])
    {
        $userlist=$this->userService->getList($request);
        $userlist=$userlist['data'];
        //组装数据
        $userdata=[];
        foreach ($userlist as $k => $v) {
            $userdata[$v['nickname']]=$v['id'];
        }
        if(isset($userdata[$data['group_name']])){
            $user_id=$userdata[$data['group_name']];
        }else{
            $user_id=0;
        }
        $data['user_id']=$user_id;
        $unique_id=$data['unique_id'];
        //获取所有json数据
        $jsonData = $request->json()->all();
        $data['json_data']=json_encode($jsonData, JSON_UNESCAPED_UNICODE);

        //dd($res);
        #插入 post 主表
        $imgs=json_decode($data['photos_url'],true);
        $cover='';
        if(!empty($imgs)){
            $cover=$imgs[0];
        }
        $group_type='4';
        if($data['group_name']=='买组'){
            $group_type='3';
        }
        $post_data=[
            'json_data'=>$data['json_data'],
            'unique_id'=>$data['unique_id'],
            'channel'=>$data['channel'],
            'article_url'=>$data['article_url'],
            'group_type'=>$group_type,
            'user_id'=>$data['user_id'],
            'nickname'=>$data['userName'],
            'avatar'=>$data['avatar'],
            'title'=>$data['title'],
            'cover'=>$cover,//默认取第一张图片
            'content_books'=>$data['content'],
            'images'=>$data['photos_url'],
            'publish_time'=>$data['publicTime'],
            'like_count'=>'0',
            'collect_count'=>'0',
            'comment_count'=>'0',
            'view_count'=>'0',
            'status'=>'1',
            'is_delete'=>'2', //是否删除 1  删除  2 不删除

        ];
        $post_data['create_time'] =date("Y-m-d H:i:s");
      
        #组装关联商品
        $guanlian_shop_arr=[];
        $content_books =json_decode($post_data['content_books'],true);
        //dd($content_books);
        foreach($content_books as $k1=>$v1){
            if($v1['type']=='link'&&$v1['product_id'] &&$v1['productImage']){
                $productUnique=platform_name_product_id($v1['platform_name'],$v1['product_id']);
                //dd($productUniqueId);
                $guanlian_shop_arr[]=[
                    "platformName"=>$v1['platform_name'],
                    "productId"=>$v1['product_id'],
                    "image"=>$v1['productImage'],
                    "title"=>$v1['title'],
                    "productUniqueId"=>$productUnique['1'],
                    "create_time"=>$post_data['create_time'],
                ];
               // dd($v1);
            }

        }
        if(!empty($guanlian_shop_arr)){
            $guanlian_shop_arr=array_values($guanlian_shop_arr);
        }
        $guanlian_shop_arr = json_encode($guanlian_shop_arr, JSON_UNESCAPED_UNICODE);

        //dd($guanlian_shop_arr);
        $post_data['guanlian_shop']=$guanlian_shop_arr;

        //dd($post_data);
        $post_info=$this->model->where(['unique_id'=>$data['unique_id']])->first();
        if($post_info){

            $this->model->where(['unique_id'=>$data['unique_id']])->update($post_data);
            $post_id=$post_info['id'];
        }else{
            
            $post_data['update_time'] =date("Y-m-d H:i:s");
            $post_id=$this->model->insertGetId($post_data);
        }

        #图片表更新
        $img_data=[
            'photos_url'=>json_decode($data['photos_url'],true),
            'post_id'=>$post_id,
            'unique_id'=>$data['unique_id'],
        ];
        $this->DoubanpostimageService->addDate($request,$img_data);
        

        $this->success1();

    }
    //帖子列表
    public function getListAppData($request,$data=[])
    {
        $page = !empty($data['page']) && intval($data['page']) ?$data['page'] :$this->cpage;
        $limit = !empty($data['limit']) && intval($data['limit']) ?$data['limit'] :$this->climit;
        //dd($page);
        $offset = ($page-1)*$limit;
        

        
        $where = [
          // ['status','=','1'],
        ];
        //是否删除  1  删除  2 不删除
        $where[]=['is_delete','=','2'];
        if(isset($data['user_id'])&&!empty($data['user_id'])){
            $where[]=['user_id','=',$data['user_id']];
        }
        if(isset($data['title'])&&!empty($data['title'])){
            $where[]=['title','like','%'.$data['title'].'%'];
        }
        if(isset($data['group_type'])&&!empty($data['group_type'])){
            $where[]=['group_type','=',$data['group_type']];
        }
        //dd($data);
        $count = $this->model->where($where)->count();
        $fields = ['id','user_id','is_official','avatar','unique_id','cover','content_books','y_content','images','title','guanlian_shop','nickname','update_time','publish_time'];
        //$this->getLastSql();
        $list = $this->model->select($fields)
        ->where($where)
        ->offset($offset)->limit($limit)
        ->orderBy('update_time', 'desc')
        ->orderBy('publish_time', 'desc')
        ->orderBy('id', 'desc')
        ->get()->toArray();

        $url=$this->getInfo;
        //dd($userdata);
        foreach($list as &$v){
            $user_id=(int)trim($v['user_id']);
            $user=$this->userService->update_user($user_id);
            $v['avatar_img'] =$user['avatar'];
            if($v['is_official']=='1'){
                $v['avatar_img'] =$v['avatar'];
            }
            
            $user_id=$v['user_id'];
            $guanlian_shop=json_decode($v['guanlian_shop'],true);
            $guajlian_ar=[];
            if($guanlian_shop){
                foreach($guanlian_shop as $k1=>$v1){
                    $platformName=$v1['platformName'];
                    $productId=$v1['productId'];
                    $data2=[
                        'platform'=>$platformName,
                        'product_id'=>$productId,
                        'user_id'=>$user_id,
                    ];
                        
                    $postdata=json_post($url,$data2);
                    if($postdata['status']=='200'){
                        $data3=$postdata['data'];
                        $v1['data']=$data3;
                        $guajlian_ar[]=$v1;

                    }
                    
                }
            }
            $v['guanlian_shop']=$guajlian_ar;
            $v['content_books'] =json_decode($v['content_books'],true);       
            $v['images'] =json_decode($v['images'],true);
            $v['save_time'] =uc_time_ago($v['update_time']);
        
        
        }
        $result = [
            'page'=> $page,
            'limit'=> $limit,
            'total_page'=> ceil($count/$limit),
            'count'=>$count,
            'data'=> $list
        ];
        return $result; 

    }
    //详情-帖子
    public function appDatadetail($request,$data=[])
    {
        $where = [
           ['id','=',$data['id']],
        ];
        $list = $this->model->where($where)->first();
        //dd($list);
        if(empty($list)){
            $this->error("帖子不存在");
        }
        //dd($list);
        $channel=$list['channel'];
        $guanlian_shop=$list['guanlian_shop'];
        if($channel=='app'){
            //$url=$this->URL_MAP[$platform];
            $url=$this->getInfo;
            $user_id=$list['user_id'];
            $list['guanlian_shop']=json_decode($list['guanlian_shop'],true);
            $list['content']=json_decode($list['content'],true);
            $guajlian_ar=[];
            if($guanlian_shop){
                foreach($guanlian_shop as $k=>$v){
                    $platformName=$v['platformName'];
                    $productId=$v['productId'];
                    $url=$this->getInfo;
                    $data2=[
                        'platform'=>$platformName,
                        'product_id'=>$productId,
                        'user_id'=>$user_id,
                    ];
                        
                    $postdata=json_post($url,$data2);
                    if($postdata['status']=='200'){
                        $data3=$postdata['data'];
                        $v['data']=$data3;
                        $guajlian_ar[]=$v;

                    }
                    
                } 
            }

            $list['guanlian_shop']=$guajlian_ar;

        }
        $list['content_books'] =json_decode($list['content_books'],true);       
        $list['images'] =json_decode($list['images'],true);
        
        return $list;
    }
    //修改-帖子
    public function editAppData($request,$data=[])
    {
        $id=$data['id'];
        $imgs=json_decode($data['photos_url'],true);
        //内容
       /* $y_content=$content=$data['content'];
        $deal_content=[];
        $deal_content[]=[
               'type'=>'text',
               'text'=>$content,
        ];
        $dealcontent = json_encode($deal_content, JSON_UNESCAPED_UNICODE);*/
        //dd($content);
        //关联商品
        $guanlian_shop=$data['guanlian_shop'];
        $where = [
           ['id','=',$id],
        ];

        $cover='';
        if(!empty($imgs)){
            $cover=$imgs[0];
        }
        $post_data=[
            'channel'=>'app',
            'user_id'=>$data['userId'],
            'nickname'=>$data['userName'],
            'avatar'=>$data['avatar'],
            'title'=>$data['title'],
            'content_books'=>$data['content'],
            'y_content'=>$data['content'],
            'images'=>$data['photos_url'],
            'publish_time'=>$data['publicTime'],
            'like_count'=>'0',
            'collect_count'=>'0',
            'comment_count'=>'0',
            'view_count'=>'0',
            'status'=>'1',
            'cover'=>$cover,
            'guanlian_shop'=>$guanlian_shop,
            'check_status'=>1,//审核状态=已发布(默认)
            'status'=>0,//显示状态(隐藏)
            'check_result'=>2,//审核结果-待审核

        ];
        $jsonData = $request->json()->all();
        $post_data['json_data']=json_encode($jsonData, JSON_UNESCAPED_UNICODE);

        $post_data['create_time'] =date("Y-m-d H:i:s");
        $res=$this->model->where($where)->update($post_data);
        $post_id=$id;
         #关联商品插入新表
        if($post_id && !empty($guanlian_shop)){
            $first=$this->model->where(['id'=>$post_id])->first();
            $post_unique_id=$first['unique_id'];
            $user_id=$first['user_id'];
            //dd($user_id);
            $this->doubanpostproductService->addData($request,$user_id,$post_unique_id,$guanlian_shop);
            
        }
        return($res);
    }
    //添加-帖子
    public function addAppData($request,$data=[])
    {
        //is_official
        $userId=$data['userId'];
        $data1=[
            'userId'=>$userId
        ];
        $isUserOfficial=$this->userService->isUserOfficial($request,$data1);
        if($isUserOfficial['code']==2){
            $is_official=2;
        }else{
            $is_official=1;
        }

        $data['unique_id']=generateRandomString();
        $imgs=json_decode($data['photos_url'],true);
        //内容
/*        $y_content=$content=$data['content'];
        $deal_content=[];
        $deal_content[]=[
               'type'=>'text',
               'text'=>$content,
        ];
        $dealcontent = json_encode($deal_content, JSON_UNESCAPED_UNICODE);*/
        //dd($content);
        //关联商品
        $guanlian_shop=$data['guanlian_shop'];
        //dd($guanlian_shop);
        

        $cover='';
        if(!empty($imgs)){
            $cover=$imgs[0];
        }
        //如果是官方账号直接状态=1
        $status=1;
        if($is_official==1){
            $status=1;
        }

        $post_data=[
            'is_delete'=>'2',
            'is_official'=>$is_official,
            'unique_id'=>$data['unique_id'],
            'channel'=>'app',
            'user_id'=>$data['userId'],
            'nickname'=>$data['userName'],
            'avatar'=>$data['avatar'],
            'title'=>$data['title'],
            'content_books'=>$data['content'],
            'y_content'=>$data['content'],
            'images'=>$data['photos_url'],
            'publish_time'=>$data['publicTime'],
            'like_count'=>'0',
            'collect_count'=>'0',
            'comment_count'=>'0',
            'view_count'=>'0',
            'cover'=>$cover,
            'guanlian_shop'=>$guanlian_shop,
            'check_status'=>1,//审核状态=已发布(默认)
            'status'=>$status,//显示状态(隐藏)
            'check_result'=>2,//审核结果-待审核
            'post_status'=>1,//已发布

        ];
        
        DB::beginTransaction();
        try{
            // 设置事务超时
            DB::statement('SET SESSION innodb_lock_wait_timeout = 10');
            $jsonData = $request->json()->all();
            $post_data['json_data']=json_encode($jsonData, JSON_UNESCAPED_UNICODE);

            $post_data['create_time'] =date("Y-m-d H:i:s");
            $post_data['update_time'] =date("Y-m-d H:i:s");
            $post_id=$this->model->insertGetId($post_data);
            #关联商品插入新表
            if($post_id && !empty($guanlian_shop)){
                $first=$this->model->where(['id'=>$post_id])->first();
                $post_unique_id=$first['unique_id'];
                $user_id=$first['user_id'];
                //dd($user_id);
                $this->doubanpostproductService->addData($request,$user_id,$post_unique_id,$guanlian_shop);
                
            }
        }catch(\Exception $e){
            DB::rollBack();
            return $this->error('提交失败'.$e->getMessage());
        }
        DB::commit();

        return $post_data;
    }
    //删除-帖子
    public function appDatadel($request,$data=[],$ids)
    {
        $res =  $this->model->whereIn('id',$ids)->delete();
        if(!$res){
            $this->error('删除失败');
        }else{
            $this->success();
        }
    }
    //删除-帖子-管理员
    public function officialDatadel($request,$data=[],$ids)
    {
        $res =  $this->model->whereIn('id',$ids)->update(['is_delete'=>'1','delete_content'=>$data['content']]);
        $hdata=$data;
        $hdata['type']=2;
        $this->admindeletelogService->addDate($request,$hdata);
        if(!$res){
            $this->error('删除失败');
        }else{
            $this->success();
        }
    }
    //列表
    public function getList($request,$data=[],$type='')
    {
        $page = intval($request->input('page')) ?$request->input('page') :$this->cpage;
        $limit = intval($request->input('limit')) ?$request->input('limit') :$this->climit;
        $offset = ($page-1)*$limit;

        //die("sdfs");

        $where=" where 1=1";
        $where.=" and status='1' ";
        //type=1  逛逛
        if($type=='1'){
            $where.=" and cover !='' ";
            $where.=" and channel='app' ";
            //是否删除 1 删除 2 不删除
            $where.=" and is_delete='2' ";
        }
        if(isset($data['title'])&&!empty($data['title'])){
            $where.=" and title like '%{$data['title']}%' ";
        }
        if(isset($data['group_type'])&&!empty($data['group_type'])){
            $where.=" and group_type = '{$data['group_type']}' ";
        }

        if(isset($data['is_official'])&&!empty($data['is_official'])){
            $where.=" and is_official = '{$data['is_official']}' ";
        }
        if($type=='1'){
            //逛逛
            $sql="SELECT `id`,`group_type`,`channel`,`user_id`,`avatar`,`is_official`,`nickname`,`unique_id`,`title`,`cover`,`view_count`,`comment_count`,`collect_count`,`sales_count`,`publish_time`,`update_time` FROM `module_douban_post` {$where}  ORDER BY publish_time DESC ";
        }else{
            $sql="SELECT `id`,`group_type`,`channel`,`user_id`,`avatar`,`is_official`,`nickname`,`unique_id`,`title`,`cover`,`view_count`,`comment_count`,`collect_count`,`sales_count`,`publish_time`,`update_time` FROM `module_douban_post` {$where}  ORDER BY update_time DESC ";
        }
       // die($sql);

        $list=DB::select($sql);
        $list = array_map('get_object_vars', $list);

        foreach ($list as &$content) {
            //$content['avatar_img']=$content['avatar'];
            $user_id=(int)trim($content['user_id']);


            if($content['group_type']=='3'){
                $user_id=901;
                $content['user_id']=$user_id;
            }else if($content['group_type']=='4'){
                $user_id=902;
                $content['user_id']=$user_id;
            }

            //$content['avatar_img'] ='http://xingfanapp.oss-cn-hangzhou.aliyuncs.com/uploads/modules/2025-06-11/f6dcc8ae-375a-4957-a59c-6aeb6b191b18.jpg';
            
            #获取昵称
            $people_id=$content['user_id'];
            
            $userlist=$this->userService->update_user($people_id);
            //dd($userlist);
            $content['nickname']=$userlist['nickname'];
            $content['avatar']=$userlist['avatar'];
            $content['avatar_img']=$userlist['avatar'];
            
            if($content['channel']=='app'){
                $content['avatar_img'] =$content['avatar'];
            }else{
                $content['publish_time'] =$content['update_time'];
            }
            //dd($user_id);
            
            $content['save_time'] =uc_time_ago($content['update_time']);

            $view_count=$content['view_count'];
            if(empty($view_count)){
                $view_count=0;
                $content['view_count']=$view_count;
            }
            $comment_count=$content['comment_count'];
            if(empty($comment_count)){
                $comment_count=0;
                $content['comment_count']=$comment_count;
            }
            $collect_count=$content['collect_count'];
            if(empty($collect_count)){
                $collect_count=0;
                $content['collect_count']=$collect_count;
            }
            $sales_count=$content['sales_count'];
            if(empty($sales_count)){
                $sales_count=0;
                $content['sales_count']=$sales_count;
            }
            $content['base_score'] = ContentScoringService::calculatePopularityScore(
                $view_count,
                $comment_count,
                $collect_count,
                $sales_count
            );
            $timestamp = strtotime($content['publish_time']); 
            #$content['publish_time']=date('m-d H:i',$timestamp);
            $content['days_passed'] = (time() - $timestamp) / 86400; // 计算天数
        }
        
        $unit_type=$data['unit_type'];
        switch ($unit_type) {
            case "1":
                //综合（按最终得分排序）
                $sortedBy = ContentScoringService::sortContents($list, 'comprehensive');
                break;
            case "2":
                // 最新（按发布时间降序）
                $sortedBy = ContentScoringService::sortContents($list, 'latest');
                break;
            case "3":
                // 最热（按浏览量降序）
                $sortedBy = ContentScoringService::sortContents($list, 'hottest');               
                break; 
             case "4":
                // 高佣金（按佣金降序）
                $sortedBy = ContentScoringService::sortContents($list, 'high_commission');           
                break; 
             case "5":
                // 高销量（按销量降序）
                $sortedBy = ContentScoringService::sortContents($list, 'high_sales');             
                break;
            default:
                //die("asdfsad");
                $sortedBy =$list;
        }
 

        $list= array_slice($sortedBy, $offset, $limit);

        $count = count($sortedBy);

        $result = [
            'page'=> $page,
            'limit'=> $limit,
            'total_page'=> ceil($count/$limit),
            'count'=>$count,
            'data'=> $list
        ];
        return $result; 
    }
    //详情
    public function dataDetail($request,$data=[])
    {
        $unique_id=$data['unique_id'];
        $people_id=$data['people_id'];
        $where = [
           ['unique_id','=',$unique_id],
        ];
        $list = $this->model->where($where)->first();
        $likeList=Doubanlike::getList();
        $collectList=Doubancollect::getList();
        //dd($collectList);
        $key="{$list['unique_id']}_{$people_id}";
        $list['is_like'] =2;
        if(isset($likeList[$key])){
            $list['is_like'] =1;
        }
        $list['is_collect'] =2;
        if(isset($collectList[$key])){
            $list['is_collect'] =1;
        }
        #获取昵称
        $people_id=$list['user_id'];
        
        $userlist=$this->userService->update_user($people_id);
        //dd($userlist);
        $list['nickname']=$userlist['nickname'];
        $list['avatar']=$userlist['avatar'];
        if(empty($list['article_url'])){
            $list['article_url']="";
        }

        if(empty($list['group_type'])){
            $list['group_type']=0;
        }

        if(empty($list['sales_count'])){
            $list['sales_count']=0;
        }
        //dd($userlist);
        $channel=$list['channel'];
        $guanlian_shop=$list['guanlian_shop'];
        if($channel=='app'){
            //$url=$this->URL_MAP[$platform];
            $url=$this->getInfo;
            $user_id=$list['user_id'];
            $list['guanlian_shop']=$guanlian_shop=json_decode($list['guanlian_shop'],true);
            $guajlian_ar=[];
            if($guanlian_shop){
                foreach($guanlian_shop as $k=>$v){
                    $platformName=$v['platformName'];
                    $productId=$v['productId'];
                    $url=$this->getInfo;
                    $data2=[
                        'platform'=>$platformName,
                        'product_id'=>$productId,
                        'user_id'=>$user_id,
                    ];

                    $postdata=json_post($url,$data2);
                    if($postdata['status']=='200'){
                        $data3=$postdata['data'];
                        $v['data']=$data3;
                        $guajlian_ar[]=$v;

                    }
                    
                }
            }
           
            $list['guanlian_shop']=$guajlian_ar;

        }
        
        if($channel=='豆瓣'){
            $guanlian_shop_arr=[];
            $content_books =json_decode($list['content_books'],true); 
            foreach($content_books as $k1=>$v1){
                if($v1['type']=='link'&&$v1['product_id'] &&$v1['productImage']){
                    $productUnique=platform_name_product_id($v1['platform_name'],$v1['product_id']);
                    //dd($productUniqueId);
                    $guanlian_shop_arr[]=[
                        "platformName"=>$v1['platform_name'],
                        "productId"=>$v1['product_id'],
                        "image"=>$v1['productImage'],
                        "title"=>$v1['title'],
                        "productUniqueId"=>$productUnique['1'],
                        "create_time"=>$list['create_time'],
                    ];
                   // dd($v1);
                }

            }
            $list['guanlian_shop']=$guanlian_shop_arr;
        }

        //dd($guanlian_shop_arr);
        $list['content_books'] =json_decode($list['content_books'],true);       
        $list['images'] =json_decode($list['images'],true);
        
        return $list;
    }
/*    // 帖子消息
    public function cardMsgList($request,$data=[])
    {
        $page = !empty($data['page']) && intval($data['page']) ?$data['page'] :$this->cpage;
        $limit = !empty($data['limit']) && intval($data['limit']) ?$data['limit'] :$this->climit;
        $offset = ($page-1)*$limit;
        $where = [
           ['check_result','=','3'],//已拒绝
           ['check_status','=','3'],//已审核
        ];
        if(isset($data['people_id'])&&!empty($data['people_id'])){

            $where[]=['user_id','=',$data['people_id']];
        }

        $fields = ['id','unique_id','user_id','title','check_content','update_time'];
        $list = $this->model->select($fields)
        ->where($where)
        ->limit($limit)
        ->orderBy('update_time', 'desc')
        ->get();
        $count = $this->model->where($where)->count();
        $total_page=count($list);
        $result=[
            'page'=>$page,
            'limit'=>$limit,
            'count'=>$count,
            'total_page'=>$total_page,
            'data'=>$list,
        ];
        
        return $result;


    }*/
   
}
